//
//  ByRegisterApiUser.m
//  oc_knowledge
//
//  Created by justiOS on 17/1/11.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByApiUser.h"
#define UPLOAD_ERROR_STRING_CODE -67
#define UPLOAD_ERROR_OTHER_CODE -76
@implementation ByApiUser

/** 发送手机验证码 */
+ (void)getCode:(ByNetParamsModel *)model
        success:(void(^)(ByNetBaseResult *result))success
        failure:(void(^)(ByNetBaseResult *result))failure {
    
    static NSString *apiType = @"By_SecurityCode_send";
    static NSInteger apiVersion = 101;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%ld%d", (NSInteger)[NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:model.mobile forKey:@"mobile"];
    [params setObject:model.type forKey:@"code_type"];
    [params setObject:@"+86" forKey:@"country"];
    // 返回的responseObject 可能是字符串也可能是字典
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeString
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notifyID) {
           
           // 若返回数据为字典类型则抛出异常
           NSAssert([responseObject isKindOfClass:[NSString class]], @"请求验证码 返回数据是字符串类型的，请检查");
           
           CodeLog(@"******** %@ 获取验证码成功: %@", apiType, responseObject);
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = 0;
           result.msg = responseObject;
           result.data = responseObject; // 验证码（6位字符串）
           result.notify_id = notifyID;
           
           if(success) {
               success(result);
           }
           
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           CodeLog(@"******** %@ 获取验证码失败: %@", apiType, error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           result.msg = error.domain;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];
    
}

/** 验证验证码 */
+ (void)checkCode:(ByNetParamsModel *)model
          success:(void(^)(ByNetBaseResult *result))success
          failure:(void(^)(ByNetBaseResult *result))failure {
    
    static NSString *apiType = @"By_SecurityCode_verify";
    static NSInteger apiVersion = 101;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%ld%d", (NSInteger)[NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:model.mobile forKey:@"mobile"];
    [params setObject:model.type forKey:@"code_type"];
    [params setObject:model.code forKey:@"code"];
    [params setObject:@"+86" forKey:@"country"];
    
    // 返回的responseObject 可能是字符串也可能是字典
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeString
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notifyID) {
           
           // 若返回数据为字典类型则抛出异常
           NSAssert([responseObject isKindOfClass:[NSString class]], @"验证验证码 返回数据是字符串类型的，请检查");
           
           CodeLog(@"******** %@ 验证验证码成功: %@", apiType, responseObject);
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = 0;
           result.msg = responseObject;
           result.data = responseObject; // 验证码（6位字符串）
           result.notify_id = notifyID;
           
           if(success) {
               success(result);
           }
           
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           CodeLog(@"******** %@ 验证验证码失败: %@", apiType, error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           result.msg = error.domain;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];
}

/** 登陆 */
+ (void)login:(ByNetParamsModel *)model
      success:(void(^)(ByNetBaseResult *result))success
      failure:(void(^)(ByNetBaseResult *result))failure {
    
    static NSString *apiType = @"By_User_login";
    static NSInteger apiVersion = 104;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%.0lf%d", [NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:model.username forKey:@"username"];
    [params setObject:model.password forKey:@"password"];
    [params setObject:@"role_driver" forKey:@"role"];
    [params setObject:@"+86" forKey:@"country"];
    // 返回的responseObject 可能是字符串也可能是字典
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeDictionary
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notifyID) {
           
           CodeLog(@"******** 登录 -> 成功: %@", responseObject);
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = 0;
           result.msg = @"登录成功";
           ByModelUser *model = [[ByModelUser alloc] initContentWithDic:responseObject];
           result.data = model;
           result.notify_id = notifyID;
           
           if(success) {
               success(result);
           }
           
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           CodeLog(@"******** 登录 -> 失败: %@", error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           result.msg = error.domain;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];
    
}

/** 注册 */
+ (void)reigster:(ByNetParamsModel *)model
         success:(void(^)(ByNetBaseResult *result))success
         failure:(void(^)(ByNetBaseResult *result))failure {
    
    static NSString *apiType = @"By_User_register";
    static NSInteger apiVersion = 102;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%ld%d", (NSInteger)[NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:model.username forKey:@"username"];
    [params setObject:model.password forKey:@"password"];
    [params setObject:@"+86" forKey:@"country"];
    [params setObject:model.code forKey:@"code"];
    [params setObject:model.from forKey:@"from"];
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeString
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notifyID) {
           
           CodeLog(@"******** 注册 -> 成功: %@", responseObject);
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = 0;
           result.msg = @"注册成功";
           result.data = responseObject;
           result.notify_id = notifyID;
           
           if(success) {
               success(result);
           }
           
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           CodeLog(@"******** 注册 -> 失败: %@", error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           result.msg = error.domain;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];
}



/** 用手机找回密码 */
+ (void)retrievePwd:(ByNetParamsModel *)model
            success:(void(^)(ByNetBaseResult *result))success
            failure:(void(^)(ByNetBaseResult *result))failure {
    
    static NSString *apiType = @"By_User_updatePwd";
    static NSInteger apiVersion = 101;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%ld%d", (NSInteger)[NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:model.username forKey:@"mobile"];
    [params setObject:model.password forKey:@"password"];
    [params setObject:@"+86" forKey:@"country"];
    [params setObject:model.code forKey:@"code"];
    // 返回的responseObject 可能是字符串也可能是字典
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeString
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notifyID) {
           
           // 返回数据为 字符串
           NSAssert([responseObject isKindOfClass:[NSString class]], @"用手机找回密码 返回数据是字符串类型的，请检查");
           
           CodeLog(@"******** 用手机找回密码 -> 成功: %@", responseObject);
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = 0;
           result.msg = responseObject;
           result.data = responseObject;
           
           if(success) {
               success(result);
           }
           
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           CodeLog(@"******** 用手机找回密码 -> 失败: %@", error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           result.msg = error.domain;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];
}

/** 手机验证码登陆 */
+ (void)loginWithCode:(ByNetParamsModel *)model
              success:(void(^)(ByNetBaseResult *result))success
              failure:(void(^)(ByNetBaseResult *result))failure {


    static NSString *apiType = @"By_User_loginByCode";
    static NSInteger apiVersion = 102;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%.0lf%d", [NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:model.mobile forKey:@"mobile"];
    [params setObject:model.code forKey:@"code"];
    [params setObject:@"role_driver" forKey:@"role"];
    [params setObject:@"+86" forKey:@"country"];
    [params setObject:@"device_id_um" forKey:@"device_token"];
    [params setObject:@"ios" forKey:@"device_type"];
    // 返回的responseObject 可能是字符串也可能是字典
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeDictionary
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notifyID) {
           
           CodeLog(@"******** 登录 -> 成功: %@", responseObject);
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = 0;
           result.msg = @"登录成功";
           ByModelUser *model = [[ByModelUser alloc] initContentWithDic:responseObject];
           result.data = model;
           result.notify_id = notifyID;
           
           if(success) {
               success(result);
           }
           
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           CodeLog(@"******** 登录 -> 失败: %@", error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           result.msg = error.domain;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];


}

/** 修改密码 */
+ (void)changePwd:(ByNetParamsModel *)model
          success:(void(^)(ByNetBaseResult *result))success
          failure:(void(^)(ByNetBaseResult *result))failure {
    
    static NSString *apiType = @"By_User_updatePwdByOldPwd";
    static NSInteger apiVersion = 100;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%ld%d", (NSInteger)[NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:model.s_id forKey:@"s_id"];
    [params setObject:model.uid forKey:@"uid"];
    [params setObject:model.old_psw forKey:@"password"];
    [params setObject:model.password forKey:@"new_password"];
    
    // 返回的responseObject 可能是字符串也可能是字典
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeString
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notifyID) {
           
           // 返回数据为 字符串
           NSAssert([responseObject isKindOfClass:[NSString class]], @"修改密码 返回数据是字符串类型的，请检查");
           
           CodeLog(@"******** 修改密码 -> 成功: %@", responseObject);
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = 0;
           result.msg = responseObject;
           result.data = responseObject;
           
           if(success) {
               success(result);
           }
           
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           CodeLog(@"******** 修改密码 -> 失败: %@", error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           result.msg = error.domain;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];
}

// 上传单个图片（头像）
+ (void)uploadImage:(UIImage *)image
               type:(NSString *)type
            success:(void(^)(NSArray *success))success
            failure:(void(^)(NSURLSessionDataTask *operation, NSError *error))failure {

    // 构造请求参数
    ByModelUser *user = [ByCacheUser getUserInfo];
    if(user == nil) return;

    // manager对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 10;
    // AFN序列化，接收内容类型为以下这些
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    // 构造网址
    NSString *strUrl = [NSString stringWithFormat:@"%@/file/upload?client_id=%@&uid=%@&type=%@",BOYE_API_URL, BOYE_CLIENT_ID,user.uid,type];

    // 处理图片
    NSData *data = UIImageJPEGRepresentation(image, 1);
    while ((data.length / 1000.0) > 500) {
        UIImage *tmp_image = [UIImage imageWithData:data];
        data = UIImageJPEGRepresentation(tmp_image, 0.5);
    }

    // 拼接请求体
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:strUrl  parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:data name:@"image" fileName:@"icon.jpg" mimeType:@"image/jpeg"];

    } error:nil];


    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {

                      NSLog(@"fractionCompleted: %f", uploadProgress.fractionCompleted);

                      // 根据请求进度刷新UI
                      dispatch_async(dispatch_get_main_queue(), ^{
                      });

                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          NSLog(@"Error: %@", error);

                          if (failure) {
                              failure(nil, error);
                          }
                      } else {
                          NSLog(@"upload:%@", responseObject);

                          NSDictionary *responseDic = responseObject;
                          if (![responseObject[@"data"] isKindOfClass:[NSArray class]]) {
                              NSError *error;
                              if ([responseObject[@"data"] isKindOfClass:[NSString class]]) {
                                  error = [NSError errorWithDomain:responseObject[@"data"] code:UPLOAD_ERROR_STRING_CODE userInfo:nil];
                              } else {
                                  error = [NSError errorWithDomain:@"未知错误!请重试" code:UPLOAD_ERROR_OTHER_CODE userInfo:nil];
                              }
                              if (failure) {
                                  failure(nil, error);
                              }
                          } else {
                              NSArray *ary = responseDic[@"data"];
                              if (success) {
                                  success(ary);
                              }
                          }

                      }
                  }];

    [uploadTask resume];
}


/** 用户资料更新 */
+ (void)updateUserInfo:(ByNetParamsModel *)model
               success:(void(^)(ByNetBaseResult *result))success
               failure:(void(^)(ByNetBaseResult *result))failure {
    
    static NSString *apiType = @"By_User_update";
    static NSInteger apiVersion = 100;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%ld%d", (NSInteger)[NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    // 必须参数
    [params setObject:model.uid forKey:@"uid"];
    [params setObject:model.s_id forKey:@"s_id"];
    if (model.nickname) {
        [params setObject:model.nickname forKey:@"nickname"];
    }
    if (model.realname) {
        [params setObject:model.realname forKey:@"realname"];
    }
    if (model.mobile) {
        [params setObject:model.mobile forKey:@"mobile"];
    }
    if (model.sex) {
        [params setObject:model.sex forKey:@"sex"];
    }
    if (model.qq) {
        [params setObject:model.qq forKey:@"qq"];
    }
    if (model.birthday) {
        [params setObject:model.birthday forKey:@"birthday"];
    }
    if (model.sign) {
        [params setObject:model.sign forKey:@"sign"];
    }
    if (model.email) {
        [params setObject:model.email forKey:@"email"];
    }
    
    // 返回的responseObject 可能是字符串也可能是字典
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeString
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notifyID) {
           
           CodeLog(@"******** 用户资料更新 -> 成功: %@", responseObject);
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = 0;
           result.msg = responseObject;
           result.data = responseObject;
           result.notify_id = notifyID;
           
           if(success) {
               success(result);
           }
           
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           CodeLog(@"******** 用户资料更新 -> 失败: %@", error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           NSDictionary *failInfoDic = @{@"-5" :@"邮箱格式不正确",
                                         @"-6" :@"邮箱长度不合法",
                                         @"-7" :@"邮箱禁止注册",
                                         @"-8" :@"邮箱被占用",
                                         @"-9" :@"手机格式不正确",
                                         @"-10":@"手机禁止注册",
                                         @"-11":@"手机号被占用",};
           NSString *errorMsg = nil;
           if ([failInfoDic.allKeys containsObject:error.domain]) {
               errorMsg = failInfoDic[error.domain];
           } else {
               errorMsg = @"未知错误";
           }
           result.msg = errorMsg;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];
}
/** 注销账户 */
+ (void)deleteAccounts:(ByNetParamsModel *)model
               success:(void(^)(ByNetBaseResult *result))success
               failure:(void(^)(ByNetBaseResult *result))failure {


    static NSString *apiType = @"By_User_delete";
    static NSInteger apiVersion = 100;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%ld%d", (NSInteger)[NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:model.mobile forKey:@"mobile"];
    
    // 返回的responseObject 可能是字符串也可能是字典
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeString
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notifyID) {
           
           // 返回数据为 字符串
           NSAssert([responseObject isKindOfClass:[NSString class]], @"删除帐户 返回数据是字符串类型的，请检查");
           
           CodeLog(@"******** 删除帐户 -> 成功: %@", responseObject);
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = 0;
           result.msg = responseObject;
           result.data = responseObject;
           
           if(success) {
               success(result);
           }
           
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           CodeLog(@"******** 删除帐户 -> 失败: %@", error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           result.msg = error.domain;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];




}

@end
